# WebRTC HTTPS 配置验证脚本
# 根据 WEBRTC_HTTPS_RULES.md 规则进行强制验证

param(
    [switch]$Fix = $false,
    [switch]$Verbose = $false
)

function Write-Info($Message, $Color = "White") {
    Write-Host $Message -ForegroundColor $Color
}

function Write-Success($Message) {
    Write-Host "✅ $Message" -ForegroundColor Green
}

function Write-Error($Message) {
    Write-Host "❌ $Message" -ForegroundColor Red
}

function Write-Warning($Message) {
    Write-Host "⚠️  $Message" -ForegroundColor Yellow
}

function Test-DockerComposeHttpsConfig {
    Write-Info "🔍 验证 Docker Compose HTTPS 配置..." "Blue"
    
    if (!(Test-Path "docker-compose.yml")) {
        Write-Error "docker-compose.yml 文件不存在"
        return $false
    }

    $content = Get-Content "docker-compose.yml" -Raw
    $violations = @()

    # 检查必需的环境变量
    $requiredEnvVars = @(
        "ASPNETCORE_URLS.*https.*5001",
        "ASPNETCORE_HTTPS_PORT=5001",
        "ASPNETCORE_Kestrel__Certificates__Default__Path",
        "ASPNETCORE_Kestrel__Certificates__Default__Password"
    )

    foreach ($envVar in $requiredEnvVars) {
        if ($envVar -eq "ASPNETCORE_URLS.*https.*5001") {
            # 特殊处理 ASPNETCORE_URLS 检查
            if ($content -match "ASPNETCORE_URLS.*https.*5001") {
                Write-Success "环境变量检查通过: ASPNETCORE_URLS (包含 HTTPS:5001)"
            } else {
                $violations += "缺失必需的环境变量: ASPNETCORE_URLS (必须包含 https 和端口 5001)"
            }
        } else {
            if ($content -match [regex]::Escape($envVar)) {
                Write-Success "环境变量检查通过: $envVar"
            } else {
                $violations += "缺失必需的环境变量: $envVar"
            }
        }
    }

    # 检查端口映射
    if ($content -notmatch '"5001:5001"') {
        $violations += "缺失必需的 HTTPS 端口映射: 5001:5001"
    } else {
        Write-Success "HTTPS 端口映射检查通过: 5001:5001"
    }

    # 检查证书卷挂载
    if ($content -notmatch './certs:/app/certs:ro') {
        $violations += "缺失必需的证书卷挂载: ./certs:/app/certs:ro"
    } else {
        Write-Success "证书卷挂载检查通过"
    }

    if ($violations.Count -gt 0) {
        Write-Error "Docker Compose 配置违规:"
        foreach ($violation in $violations) {
            Write-Host "  • $violation" -ForegroundColor Red
        }
        return $false
    }

    Write-Success "Docker Compose HTTPS 配置验证通过"
    return $true
}

function Test-CertificateFiles {
    Write-Info "🔍 验证证书文件..." "Blue"
    
    if (!(Test-Path "certs")) {
        Write-Error "证书目录 'certs' 不存在"
        if ($Fix) {
            Write-Info "尝试创建证书目录并生成证书..." "Yellow"
            New-Item -ItemType Directory -Path "certs" -Force
            & ".\scripts\generate-dev-cert.ps1"
        }
        return $false
    }

    $certFile = "certs\webrtc-dev.pfx"
    if (!(Test-Path $certFile)) {
        Write-Error "证书文件不存在: $certFile"
        if ($Fix) {
            Write-Info "尝试生成证书..." "Yellow"
            & ".\scripts\generate-dev-cert.ps1"
        }
        return $false
    }

    # 检查证书有效期
    try {
        $cert = Get-PfxCertificate -FilePath $certFile
        $daysUntilExpiry = ($cert.NotAfter - (Get-Date)).Days
        
        if ($daysUntilExpiry -lt 30) {
            Write-Warning "证书将在 $daysUntilExpiry 天后过期，建议更新"
        } else {
            Write-Success "证书有效期检查通过 (有效期至: $($cert.NotAfter))"
        }
    }
    catch {
        Write-Error "无法读取证书文件: $($_.Exception.Message)"
        return $false
    }

    Write-Success "证书文件验证通过"
    return $true
}

function Test-HttpsScripts {
    Write-Info "🔍 验证 HTTPS 相关脚本..." "Blue"
    
    $requiredScripts = @(
        "scripts\generate-dev-cert.ps1",
        "scripts\setup-docker-https.ps1"
    )

    foreach ($script in $requiredScripts) {
        if (!(Test-Path $script)) {
            Write-Error "缺失必需的脚本: $script"
            return $false
        } else {
            Write-Success "脚本检查通过: $script"
        }
    }

    return $true
}

function Test-RulesDocumentation {
    Write-Info "🔍 验证规则文档..." "Blue"
    
    if (!(Test-Path "WEBRTC_HTTPS_RULES.md")) {
        Write-Error "缺失关键规则文档: WEBRTC_HTTPS_RULES.md"
        return $false
    }

    $content = Get-Content "WEBRTC_HTTPS_RULES.md" -Raw
    if ($content -notmatch "绝对禁止移除 HTTPS 配置") {
        Write-Error "规则文档内容不完整"
        return $false
    }

    Write-Success "规则文档验证通过"
    return $true
}

function Test-HttpsEndpoint {
    Write-Info "🔍 测试 HTTPS 端点..." "Blue"
    
    try {
        # 检查容器是否运行
        $container = docker ps --filter "name=webrtc-signaling-server" --format "table {{.Names}}\t{{.Status}}"
        if ($container -match "webrtc-signaling-server.*Up") {
            Write-Success "WebRTC 容器正在运行"
            
            # 测试 HTTPS 端点
            try {
                $response = Invoke-WebRequest -Uri "https://localhost:5001/health" -SkipCertificateCheck -TimeoutSec 10
                if ($response.StatusCode -eq 200) {
                    Write-Success "HTTPS 端点响应正常"
                    return $true
                }
            }
            catch {
                Write-Warning "HTTPS 端点测试失败: $($_.Exception.Message)"
                return $false
            }
        } else {
            Write-Warning "WebRTC 容器未运行，跳过端点测试"
            # 容器未运行不影响配置验证结果
            return $true
        }
    }
    catch {
        Write-Warning "无法检查容器状态: $($_.Exception.Message)"
        # 无法检查容器状态不影响配置验证结果
        return $true
    }
    
    return $true
}

# 主验证流程
Write-Info "================================================" "Cyan"
Write-Info "   WebRTC HTTPS 配置验证工具" "Cyan"
Write-Info "   基于 WEBRTC_HTTPS_RULES.md 规则" "Cyan"
Write-Info "================================================" "Cyan"

$allPassed = $true

# 执行所有验证
$tests = @(
    { Test-RulesDocumentation },
    { Test-DockerComposeHttpsConfig },
    { Test-CertificateFiles },
    { Test-HttpsScripts },
    { Test-HttpsEndpoint }
)

foreach ($test in $tests) {
    $result = & $test
    if (!$result) {
        $allPassed = $false
    }
    Write-Host ""
}

# 总结报告
Write-Info "================================================" "Cyan"
if ($allPassed) {
    Write-Success "🎉 所有 HTTPS 配置验证通过！"
    Write-Info "WebRTC 视频通话功能应该正常工作" "Green"
    Write-Info ""
    Write-Info "🌐 访问地址:" "Cyan"
    Write-Info "  HTTPS: https://localhost:5001 (推荐)" "Green"
    Write-Info "  HTTP:  http://localhost:5000  (仅限调试)" "Yellow"
} else {
    Write-Error "🚨 HTTPS 配置验证失败！"
    Write-Warning "WebRTC 视频通话功能可能无法正常工作"
    Write-Info ""
    Write-Info "🔧 建议修复步骤:" "Yellow"
    Write-Info "  1. 运行: .\scripts\validate-https-config.ps1 -Fix" "Cyan"
    Write-Info "  2. 检查: .\scripts\generate-dev-cert.ps1" "Cyan"
    Write-Info "  3. 部署: docker-compose up -d --build" "Cyan"
    Write-Info "  4. 验证: .\scripts\validate-https-config.ps1" "Cyan"
}
Write-Info "================================================" "Cyan"

if (!$allPassed) {
    exit 1
} 